
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSONObject;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuResult;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.order.HuiFuPayOrderCloseResultDto;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.order.HuiFuPayOrderQueryDto;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.order.HuiFuPayOrderRefundResultDto;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.order.HuiFuScanPayOrderResultDto;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.order.RefundOrderDO;
import com.hlkj.pay.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @author HlpayTeam
 * @date 2024/09/26 10:25
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class HuiFuPayOrderResponseParamsHandler {



    /**
     * 正扫提交订单参数处理
     * 
     * @param response
     * @param channelMerchantAccessContext
     */
    public static void processSubmitOrderResultData(Map<String, Object> response, ChannelPayOrderContext channelMerchantAccessContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantAccessContext.setRemark("斗拱提交支付订单返回信息为空");
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HuiFuScanPayOrderResultDto scanPayOrderResultDto = JSONObject.parseObject(response.toString(), HuiFuScanPayOrderResultDto.class);
        log.info("斗拱提交支付订单返回信息response:{}", JsonUtils.toJsonString(response));
        // 参数组装
        if (scanPayOrderResultDto.isSuccess()) {
            if (scanPayOrderResultDto.getTrans_stat() != null) {
                // P：处理中，S：成功，F：失败；交易状态以此字段为准。示例值：S
                switch (scanPayOrderResultDto.getTrans_stat()) {
                    case "P":
                        channelMerchantAccessContext.setPayOrderStatus(PayOrderEnums.PAY_ORDER_STATUS.PAYING);
                        break;
                    case "S":
                        channelMerchantAccessContext.setPayOrderStatus(PayOrderEnums.PAY_ORDER_STATUS.SUCCESS);
                        break;
                    case "F":
                        channelMerchantAccessContext.setPayOrderStatus(PayOrderEnums.PAY_ORDER_STATUS.FAIL);
                        break;
                    case "I":
                        channelMerchantAccessContext.setPayOrderStatus(PayOrderEnums.PAY_ORDER_STATUS.PAYING);
                        break;
                    default:
                }
            }
            channelMerchantAccessContext.setChannelOrderId(scanPayOrderResultDto.getHf_seq_id());
            if (scanPayOrderResultDto.getQr_code() != null) {
                channelMerchantAccessContext.setPayDataType(PayOrderEnums.PAY_DATA_TYPE.URL.getCode());
                channelMerchantAccessContext.setPayInfo(scanPayOrderResultDto.getQr_code());
            }
            else if (scanPayOrderResultDto.getPay_info() != null) {
                channelMerchantAccessContext.setPayDataType(PayOrderEnums.PAY_DATA_TYPE.DATA.getCode());
                channelMerchantAccessContext.setPayInfo(scanPayOrderResultDto.getPay_info());
            }
            // channelMerchantAccessContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
        }
        else {
            String respDesc = scanPayOrderResultDto.getResp_desc();
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantAccessContext.setRemark(respDesc);
            }
            else {
                channelMerchantAccessContext.setRemark("斗拱提交支付订单返回错误信息为空,错误码为:" + scanPayOrderResultDto.getResp_code());
            }

        }
    }

    /**
     * 订单查询参数处理
     * 
     * @param response
     * @param channelMerchantAccessContext
     */
    public static void processQueryOrderResultData(Map<String, Object> response, ChannelPayOrderQueryContext channelMerchantAccessContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantAccessContext.setRemark("斗拱查询支付订单返回信息为空");
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        PayOrderDO updartePayOrderDO = new PayOrderDO();
        log.info("斗拱查询支付订单返回信息response:{}", JsonUtils.toJsonString(response));
        // 参数组装
        HuiFuPayOrderQueryDto huiFuPayOrderQueryDto = JSONObject.parseObject(response.toString(), HuiFuPayOrderQueryDto.class);
        if (huiFuPayOrderQueryDto.isSuccess() || huiFuPayOrderQueryDto.isDoing()) {
            // Object outTransId = response.get("out_trans_id");
            // Object payInfo = response.get("pay_info");
            // Object qrCode = response.get("qr_code");
            // Object transStat = response.get("trans_stat");
            // Object endTime = response.get("end_time");
            // Object atuSubMerId = response.get("atu_sub_mer_id");
            // Object settlementAmt = response.get("settlement_amt");
            // Object feeAmt = response.get("fee_amt");
            updartePayOrderDO.setInsOrderNo(huiFuPayOrderQueryDto.getOut_trans_id());
            updartePayOrderDO.setAtuSubMerId(huiFuPayOrderQueryDto.getAtu_sub_mer_id());
            if (huiFuPayOrderQueryDto.getSettlement_amt() != null) {
                updartePayOrderDO.setSettlementAmount(new BigDecimal(huiFuPayOrderQueryDto.getSettlement_amt()));
            }
            // updartePayOrderDO.setChannelFeeAmount(feeAmt != null ? new
            // BigDecimal(feeAmt.toString()) : null);
            if (huiFuPayOrderQueryDto.getEnd_time() != null) {
                try {
                    updartePayOrderDO.setSuccessTime(DateUtils.shanghaiDate(huiFuPayOrderQueryDto.getEnd_time()));
                }
                catch (Exception e) {
                    log.error("汇付订单查询返回 时间格式化错误 dateTime:{},message:{}", huiFuPayOrderQueryDto.getEnd_time(), e.getMessage());
                }
            }
            if (huiFuPayOrderQueryDto.getQr_code() != null) {
                channelMerchantAccessContext.setPayDataType(PayOrderEnums.PAY_DATA_TYPE.URL.getCode());
                channelMerchantAccessContext.setPayInfo(huiFuPayOrderQueryDto.getQr_code());
            }
            else if (huiFuPayOrderQueryDto.getPay_info() != null) {
                channelMerchantAccessContext.setPayDataType(PayOrderEnums.PAY_DATA_TYPE.DATA.getCode());
                channelMerchantAccessContext.setPayInfo(huiFuPayOrderQueryDto.getPay_info());
            }

            if (StringUtils.hasText(huiFuPayOrderQueryDto.getWx_response())) {
                JSONObject wxObj = JSONObject.parseObject(huiFuPayOrderQueryDto.getWx_response());
                updartePayOrderDO.setUserId(wxObj.getString("openid"));
            }

            if (StringUtils.hasText(huiFuPayOrderQueryDto.getAlipay_response())) {
                JSONObject alipayObj = JSONObject.parseObject(huiFuPayOrderQueryDto.getAlipay_response());
                updartePayOrderDO.setUserId(alipayObj.getString("buyer_id"));
            }

            if (huiFuPayOrderQueryDto.getTrans_stat() != null) {
                // P：处理中；S：成功；F：失败；I: 初始
                switch (huiFuPayOrderQueryDto.getTrans_stat()) {
                    case "P":
                    case "I":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    case "S":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.SUCCESS.getCode());
                        break;
                    case "F":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.FAIL.getCode());
                        updartePayOrderDO.setBankMsg(huiFuPayOrderQueryDto.getBank_desc());
                        break;
                    default:
                }
            }
            channelMerchantAccessContext.setUpdartePayOrderDO(updartePayOrderDO);
            // channelMerchantAccessContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
        }
        else {
            String respDesc = huiFuPayOrderQueryDto.getResp_desc();
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantAccessContext.setRemark(respDesc);
            }
            else {
                channelMerchantAccessContext.setRemark("斗拱提交支付订单返回错误信息为空,错误码为:" + huiFuPayOrderQueryDto.getResp_code());
            }

        }
    }

    /**
     * 关闭订单参数处理
     * 
     * @param response
     * @param channelMerchantAccessContext
     */
    public static void processCloseOrderResultData(Map<String, Object> response, ChannelPayOrderQueryContext channelMerchantAccessContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantAccessContext.setRemark("斗拱关闭支付订单返回信息为空");
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        // 参数组装
        // Map<String,Object> data = (Map<String,Object>)response.get("data");
        // String respCode = response.get("resp_code").toString();
        HuiFuResult<HuiFuPayOrderCloseResultDto> parseObject = JSONObject.parseObject(response.toString(), new TypeReference<HuiFuResult<HuiFuPayOrderCloseResultDto>>() {
        });
        HuiFuPayOrderCloseResultDto huiFuPayOrderCloseResultDto = parseObject.getData();
        PayOrderDO updartePayOrderDO = new PayOrderDO();
        if (huiFuPayOrderCloseResultDto.isSuccess()) {
            // 关单状态
            if (huiFuPayOrderCloseResultDto.getTrans_stat() != null) {
                // P：处理中；S：成功；F：失败；
                switch (huiFuPayOrderCloseResultDto.getTrans_stat()) {
                    case "S":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                        break;
                    case "P":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSEING.getCode());
                        break;
                    default:
                }
            }
            channelMerchantAccessContext.setUpdartePayOrderDO(updartePayOrderDO);
            // channelMerchantAccessContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
        }
        else if (huiFuPayOrderCloseResultDto.isDoing()) {
            updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSEING.getCode());
            channelMerchantAccessContext.setUpdartePayOrderDO(updartePayOrderDO);
            // channelMerchantAccessContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
        }
        else {
            String respDesc = huiFuPayOrderCloseResultDto.getResp_desc();
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantAccessContext.setRemark(respDesc);
            }
            else {
                channelMerchantAccessContext.setRemark("斗拱关闭支付订单返回错误信息为空,错误码为:" + huiFuPayOrderCloseResultDto.getResp_code());
            }

        }
    }

    /**
     * 订单退款参数处理
     * 
     * @param response
     * @param channelMerchantAccessContext
     */
    public static void processRefundOrderResultData(Map<String, Object> response, ChannelRefundPayOrderContext channelMerchantAccessContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantAccessContext.setRemark("斗拱退款查询返回信息为空");
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        log.info("斗拱提交退款订单返回信息response:{}", JsonUtils.toJsonString(response));
        HuiFuPayOrderRefundResultDto huiFuPayOrderCloseResultDto = JSONObject.parseObject(response.toString(), HuiFuPayOrderRefundResultDto.class);

        // 参数组装
        // Map<String,Object> data = (Map<String,Object>)response.get("data");
        // String respCode = response.get("resp_code").toString();
        RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
        if (huiFuPayOrderCloseResultDto.isSuccess()) {
            // Object transStat = response.get("trans_stat");
            // Object bankCode = response.get("bank_code");
            // Object bankMessage = response.get("bank_message");
            // Object transFinishTime = response.get("trans_finish_time");
            updateRefundOrderDO.setBankCode(huiFuPayOrderCloseResultDto.getBank_code());
            updateRefundOrderDO.setBankMsg(huiFuPayOrderCloseResultDto.getBank_message());
            if (huiFuPayOrderCloseResultDto.getTrans_finish_time() != null) {
                try {
                    updateRefundOrderDO.setSuccessTime(DateUtils.shanghaiDate(huiFuPayOrderCloseResultDto.getTrans_finish_time()));
                }
                catch (Exception e) {
                    log.error("汇付退款查询 时间格式处理失败 transFinishTime:{},message:{}", huiFuPayOrderCloseResultDto.getTrans_finish_time(), e.getMessage());
                }

            }
            // 关单状态
            if (huiFuPayOrderCloseResultDto.getTrans_stat() != null) {
                // P：处理中；S：成功；F：失败；
                switch (huiFuPayOrderCloseResultDto.getTrans_stat()) {
                    case "P":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUNDING.getCode());
                        break;
                    case "S":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUND.getCode());
                        break;
                    case "F":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.FAIL.getCode());
                        break;
                    default:
                }
            }
            channelMerchantAccessContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            // channelMerchantAccessContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
        }
        else if (huiFuPayOrderCloseResultDto.isDoing()) {
            // channelMerchantAccessContext.setProcessStatus(CommonEnum.YES_NO_TYPE.YES);
        }
        else {
            String respDesc = huiFuPayOrderCloseResultDto.getResp_desc();
            channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantAccessContext.setRemark(respDesc);
            }
            else {
                channelMerchantAccessContext.setRemark("斗拱关闭支付订单返回错误信息为空,错误码为:" + huiFuPayOrderCloseResultDto.getResp_code());
            }
        }
    }

    /**
     * 
     * @param servletRequest
     * @return
     */
    public static PayOrderDO orderStatusParse(HttpServletRequest servletRequest) {
        String request = servletRequest.getParameter("req");
        HuiFuResult<HuiFuPayOrderQueryDto> parseObject = JSONObject.parseObject(request, new TypeReference<HuiFuResult<HuiFuPayOrderQueryDto>>() {
        });
        HuiFuPayOrderQueryDto huiFuPayOrderCloseResultDto = parseObject.getData();
        // String respCode = response.get("resp_code").toString();
        if (huiFuPayOrderCloseResultDto.isSuccess()) {
            PayOrderDO updartePayOrderDO = new PayOrderDO();
            // Object outTransId = response.get("out_trans_id");
            // Object transStat = response.get("trans_stat");
            // Object endTime = response.get("end_time");
            // Object atuSubMerId = response.get("atu_sub_mer_id");
            // Object settlementAmt = response.get("settlement_amt");
            updartePayOrderDO.setInsOrderNo(huiFuPayOrderCloseResultDto.getOut_trans_id());
            updartePayOrderDO.setAtuSubMerId(huiFuPayOrderCloseResultDto.getAtu_sub_mer_id());
            if (huiFuPayOrderCloseResultDto.getSettlement_amt() != null) {
                updartePayOrderDO.setSettlementAmount(new BigDecimal(huiFuPayOrderCloseResultDto.getSettlement_amt()));

            }
            if (huiFuPayOrderCloseResultDto.getEnd_time() != null) {
                try {
                    updartePayOrderDO.setSuccessTime(DateUtils.shanghaiDate(huiFuPayOrderCloseResultDto.getEnd_time()));
                }
                catch (Exception e) {
                    log.error("汇付订单查询返回 时间格式化错误 dateTime:{},message:{}", huiFuPayOrderCloseResultDto.getEnd_time(), e.getMessage());
                }
            }
            if (huiFuPayOrderCloseResultDto.getTrans_stat() != null) {
                // P：处理中；S：成功；F：失败；I: 初始
                switch (huiFuPayOrderCloseResultDto.getTrans_stat()) {
                    case "P":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    case "S":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.SUCCESS.getCode());
                        break;
                    case "F":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.FAIL.getCode());
                        break;
                    case "I":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    default:
                }
            }
            return updartePayOrderDO;
        }
        return null;
    }

    /**
     * 
     * @param callBackBody
     * @return
     */
    public static PayOrderDO closeOrderStatusParse(HttpServletRequest servletRequest) {
        String callBackBody = servletRequest.getParameter("req");
        HuiFuResult<HuiFuPayOrderCloseResultDto> parseObject = JSONObject.parseObject(callBackBody, new TypeReference<HuiFuResult<HuiFuPayOrderCloseResultDto>>() {
        });
        HuiFuPayOrderCloseResultDto huiFuPayOrderCloseResultDto = parseObject.getData();
        // String respCode = response.get("resp_code").toString();
        if (huiFuPayOrderCloseResultDto.isSuccess()) {
            // Object transStat = response.get("trans_stat");
            PayOrderDO payOrderDO = new PayOrderDO();
            // 关单状态
            if (huiFuPayOrderCloseResultDto.getTrans_stat() != null) {
                // P：处理中；S：成功；F：失败；
                switch (huiFuPayOrderCloseResultDto.getTrans_stat()) {
                    case "S":
                        payOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                        break;
                    case "P":
                        payOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSEING.getCode());
                        break;
                    default:
                }
            }
            return payOrderDO;
        }
        return null;
    }

    /**
     * 
     * @param callBackBody
     * @return
     */
    public static RefundOrderDO refundStatusParse(HttpServletRequest servletRequest) {
        String callBackBody = servletRequest.getParameter("req");
        HuiFuResult<HuiFuPayOrderRefundResultDto> parseObject = JSONObject.parseObject(callBackBody, new TypeReference<HuiFuResult<HuiFuPayOrderRefundResultDto>>() {
        });
        HuiFuPayOrderRefundResultDto payOrderRefundResultDto = parseObject.getData();
        RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
        if (payOrderRefundResultDto.isSuccess()) {
            // Object transStat = response.get("trans_stat");
            // Object bankCode = response.get("bank_code");
            // Object bankMessage = response.get("bank_message");
            // Object transFinishTime = response.get("trans_finish_time");
            updateRefundOrderDO.setBankCode(payOrderRefundResultDto.getBank_code());
            updateRefundOrderDO.setBankMsg(payOrderRefundResultDto.getBank_message());
            if (payOrderRefundResultDto.getTrans_finish_time() != null) {
                try {
                    updateRefundOrderDO.setSuccessTime(DateUtils.shanghaiDate(payOrderRefundResultDto.getTrans_finish_time()));
                }
                catch (Exception e) {
                    log.error("汇付退款查询 时间格式处理失败 transFinishTime:{},message:{}", payOrderRefundResultDto.getTrans_finish_time(), e.getMessage());
                }

            }
            // 关单状态
            if (payOrderRefundResultDto.getTrans_stat() != null) {
                // P：处理中；S：成功；F：失败；
                switch (payOrderRefundResultDto.getTrans_stat()) {
                    case "P":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.ORDER_REFUND_STATUS.REFUNDING.getCode());
                        break;
                    case "S":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.ORDER_REFUND_STATUS.REFUND.getCode());
                        break;
                    case "F":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.ORDER_REFUND_STATUS.FAIL.getCode());
                        break;
                    default:
                }
            }
            return updateRefundOrderDO;
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.format(LocalDateTime.now().plusMinutes(30), "yyyyMMddHHmmss"));
        System.out.println(LocalDateTime.parse("20091225091010", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
    }
}
